package com.surazezhu.xunwuproject.service.user;

import com.surazezhu.xunwuproject.entity.Role;
import com.surazezhu.xunwuproject.entity.User;
import com.surazezhu.xunwuproject.repository.RoleRepository;
import com.surazezhu.xunwuproject.repository.UserRepository;
import com.surazezhu.xunwuproject.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 设立roles表，根据userid查询role表，
 * @author:SuarezZhu Date:2018/8/8 Time:19:07
 */
@Service
public class UserServiceImpl  implements IUserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;
    @Override
    public User findUserByName(String userName) {
       User user= userRepository.findByName(userName);//是这里返回的user是一个对象
    if(user==null){
        return null;
    }
   List<Role> roles= roleRepository.findRolesByUserId(user.getId());//user的id 是role的user_id
    if(roles==null || roles.isEmpty()){
    throw  new DisabledException("权限非法");
    }
    //todo 这里逻辑没看懂，为什么user也是list
        List<GrantedAuthority> authorities = new ArrayList<>();
        roles.forEach(role -> authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName())));
        user.setAuthorityList(authorities);//将role表里的name权限赋值给user属性，（admin，user）得到[ROLE_ADMIN]
        return user;
    }
}
